package model

import (
	"fmt"
	"time"

	"github.com/Unknwon/com"
	jsoniter "github.com/json-iterator/go"
	"github.com/levigross/grequests"

	"gitee.com/goframe/lt-collector/libs/libce"
	"gitee.com/goframe/lt-collector/libs/orma"
	"gitee.com/goframe/lt-collector/libs/utils"
)

type (
	ByData struct {
		NextIssue interface{}    `json:"next_phase"`
		Issue     interface{}    `json:"open_phase"`
		OpenTime  *orma.JSONTime `json:"open_time"`
		OpenCode  string         `json:"open_result"`
	}
	ByCollector struct {
		orma.BaseModel `xorm:"extends"`

		Gid     int64  `json:"gid" xorm:"notnull comment(彩种ID)"`
		LotCode string `json:"lot_code" xorm:"varchar(20) notnull comment(接口绑定彩种参数)"`
	}
)

func (k *ByData) GetOpenIssue() string {
	return com.ToStr(k.Issue)
}

func (k *ByData) GetOpenCode() string {
	return k.OpenCode
}

func (k *ByData) GetOpenTime() orma.JSONTime {
	return *k.OpenTime
}

func (m *ByCollector) getByGid(gid int64) error {
	return libce.CacheBindModelByKey(m, fmt.Sprintf("gid:%d", gid), func() error {
		err := orma.NormalGet(m.Session().Where("gid=?", gid).Get(m))
		if err == orma.ErrOrmNotFound {
			err = fmt.Errorf("采集错误:Gid:[%d]未设置采集点参数", gid)
		}
		return err
	})
}

func (m *ByCollector) GetParam() (paramString string, err error) {
	paramString = fmt.Sprintf("?code=%s", m.LotCode)
	return
}

func (m *ByCollector) GetData(apiURL string) (data RequestData, err error) {
	rq := utils.NewRequester()
	rq.SetOption(&grequests.RequestOptions{
		UserAgent:   utils.UserAgent,
		DialTimeout: time.Second * 2,
	})
	rq.SetUrl(apiURL)
	type Result struct {
		Status int                  `json:"status"`
		Msg    string               `json:"msg"`
		Data   *jsoniter.RawMessage `json:"data"`
	}
	rq.SetRequestFunc(func(rp *grequests.Response) (e error) {
		bts := rp.Bytes()
		rstBean := new(Result)
		if e = json.Unmarshal(bts, rstBean); e != nil {
			return
		}
		if rstBean.Status != 1 {
			return fmt.Errorf("获取到的接口内容:%s", bts)
		}
		dt := new(ByData)
		if e = json.Unmarshal(*rstBean.Data, dt); e != nil {
			return fmt.Errorf("解析RawMessage失败:%s", e.Error())
		}
		data = dt
		return
	})
	for {
		err = rq.Request(utils.GET)
		if err != nil {
			log.Printf("访问[必赢]接口失败:[%s];等待3秒后继续请求\n", err.Error())
			sleepWait := time.Second * 3
			time.Sleep(sleepWait)
		} else {
			break
		}
	}
	return
}

func (m *ByCollector) AfterDelete() {
	libce.DeleteCacheByKey(m, fmt.Sprintf("gid:%d", m.Gid))
}

func (m *ByCollector) AfterUpdate() {
	libce.DeleteCacheByKey(m, fmt.Sprintf("gid:%d", m.Gid))
}
